// pages/shop/info.js
const app = getApp();
const util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 250,
    id: "",
    chooseShow: false,
    maskShow: false,
    imghidden: true,
    infoShow: false,
    goods: [],
    stroageGoods: [],
    shopInfo: {},
    article: ""
  },

  //查看大图
  previewPic(event) {
    console.log("previewPic");
    var src = event.currentTarget.dataset.src;
    console.log(src);
    //var imgList = event.currentTarget.dataset.list;// 
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: this.data.imgUrls // 需要预览的图片http链接列表
    })
  },

  //切换3d
  changeImgShow(e) {
    // console.log(e.currentTarget.dataset.url)
    var url = escape(e.currentTarget.dataset.url)
    var name = this.data.goods.product_title
    var imgUrl = this.data.goods.product_pic
    var productSn = this.data.goods.product_sn
    var shopId = this.data.goods.shop_id
    // console.log(url + "+" + name)
    //统计
    const tjData = {}; 
    tjData.shop_id = shopId;
    tjData.product_sn = productSn;
    tjData.product_url = 'product/detail?product_sn=' + productSn;
    tjData.vr_url = url;
    this.addTj(tjData);
    
    wx.navigateTo({
      url: 'webview?viewSrc=' + url + '&name=' + name + '&imageUrl=' + imgUrl
    })
 
   

  },
  //扫描二维码
  openScanCode() {
    // console.log("扫描二维码")
    wx.scanCode({
      success: (res) => {
        // console.log(res.result)
        var codeUrl = res.result;
        codeUrl = this.getProductSn(codeUrl)
        wx.redirectTo({
          url: 'info?id=' + codeUrl
        })
      }
    })
  },
  getProductSn(url) {
    url = decodeURIComponent(url);
    return url.replace("https://www.leuar.com/qrcode/", "");
  },
  changeInfoShow() {
    var show = this.data.infoShow;
    this.setData({
      infoShow: !show,
      maskShow: !show
    })
  },
  //点击弹出
  chooseSezi: function (e) {
    var show = this.data.chooseShow;
    this.setData({
      chooseShow: !show,
      maskShow: !show
    })
  },
  //弹出离开
  hideModal: function (e) {
    var that = this;
    that.setData({
      chooseShow: false,
      infoShow: false,
      maskShow: false,
    })
  },
  //打电话
  callPhone(e) {
    var phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone //仅为示例，并非真实的电话号码
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let product_sn = '';
    if (options.q) {
      product_sn = this.getProductSn(options.q);
    } else {
      product_sn = options.id;
    }

    this.showInfo(product_sn);

    //初始化用户信息
    this.getUserInfo();

  },
  recordInfo() {
    var that = this;
    var data = {};
    var date = util.formatDate(new Date);
    var id = that.data.goods.product_sn;
    var flag = wx.getStorageSync('shopList');
    if (flag) {
      if (flag.hasOwnProperty(date)) {
        for (let i in flag) {
          // console.log(flag[i])
          for (let j = 0; j < flag[i].length; j++) {
            console.log(flag[i][j].product_sn)
            if (flag[i][j].product_sn === id) {
              return;
            }
          }
        }
        flag[date].push(that.data.goods);
        wx.setStorage({
          key: "shopList",
          data: flag
        })
      } else {
        for (let i in flag) {
          // console.log(flag[i])
          for (let j = 0; j < flag[i].length; j++) {
            console.log(flag[i][j].product_sn)
            if (flag[i][j].product_sn === id) {
              return;
            }
          }
        }
        flag[date] = [];
        flag[date].push(that.data.goods);
        wx.setStorage({
          key: "shopList",
          data: flag
        })
      }
    } else {
      data[date] = [];
      data[date].push(that.data.goods);
      wx.setStorage({
        key: "shopList",
        data: data
      })
    }

  },
  openMap() {
    var longitude = Number(this.data.shopInfo.shop_longitude)
    var latitude = Number(this.data.shopInfo.shop_latitude)
    wx.openLocation({
      longitude: longitude,
      latitude: latitude,
      name: this.data.shopInfo.shop_name,
      address: this.data.shopInfo.shop_address,
      scale: 10
    })
  },
  retungo(){
    wx.navigateTo({
      url: 'index'
    })
  },
  showInfo(product_sn) {
    var that = this;
    wx.request({
      url: app.apiURL + 'product/detail', //仅为示例，并非真实的接口地址
      data: {
        "product_sn": product_sn
      },
      method: "GET",
      success: function (res) {
        var goods = res.data.data;
        wx.setNavigationBarTitle({
          title: goods.product_title
        })
        var shopInfo = goods.shop_info
        var article = goods.product_intro;
        // console.log(article);
        // console.log(goods.product_intro);   
        WxParse.wxParse('article', 'html', goods.product_intro, that, 5)     
        that.setData({
          goods: goods,
          shopInfo: shopInfo,
          imgUrls: goods.product_album 
        })

        const product_url="";
        const tjData = {}; 
        tjData.shop_id = goods.shop_id;
        tjData.product_sn = goods.product_sn;
        tjData.product_url = 'product/detail?product_sn=' + product_sn;
        tjData.vr_url = '';
        that.addTj(tjData);

        if (shopInfo) {
          that.recordInfo();
        } else {
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.mapCtx = wx.createMapContext('myMap')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //查看大图
  openPhoto() {
    var arr = [];
    arr.push(this.data.shopInfo.shop_navi)
    wx.previewImage({
      current: this.data.shopInfo.shop_navi, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.goods.product_title,
      path: 'pages/shop/info?id=' + this.data.goods.product_sn
    }
  },
  addTj: function (tjData){

    if (app.globalData.openid){
      wx.request({
        url: app.apiURL + 'tj/product', //仅为示例，并非真实的接口地址
        data: {
          "openid": app.globalData.openid,
          "shop_id": tjData.shop_id,
          "product_sn": tjData.product_sn,
          "product_url": tjData.product_url,
          "vr_url": tjData.vr_url,
        },
        method: "GET",
        success: function (res) {

        }
      })
    }

  },

  getUserInfo: function (e) {
    console.log(e)
    
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      this.initUserInfo();
    }
  },
 
  initUserInfo: function () {
    console.log("initUserInfo")
    const openid = wx.getStorageSync('openid');
    const that = this;
    if (openid) {
      wx.getUserInfo({
        success: function (res) {
          that.setLoginByUserInfo(openid, res.userInfo);
        },
        fail: function () {
          console.log("获取失败1！");
          that.initUserInfoFail();
        },
        complete: function () {
          // complete
          console.log("获取用户信息完成！")
        }
      })
    } else {
      //openid为空
      wx.login({
        success: function (res) {
          console.log(res.code)
          if (res.code) {
            wx.getUserInfo({
              withCredentials: true,
              success: function (res_user) {
                that.setLoginByWeixin(res.code, res_user);
              }, fail: function () {
                console.log("获取失败2！");
                that.initUserInfoFail();
              }, complete: function (res) {

              }
            })
          }
        }
      })
    }
  },


  setLoginByWeixin: function (code, res_user) {
    const that = this;
    wx.request({
      url: app.apiURL + 'auth/loginByWeixin',
      data: {
        code: code,
        encryptedData: res_user.encryptedData,
        iv: res_user.iv
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        //that.globalData.userInfo = JSON.parse(res.data);
        //that.globalData.openid = res.data.openId;
        const userInfo = res.data.data.userInfo;
        //wx.setStorageSync('openid', userInfo.openId);
        wx.setStorageSync('userInfo', userInfo);

        //
        const goods = that.data.goods;
        if(goods){
          const tjData = {};
          tjData.shop_id = goods.shop_id;
          tjData.product_sn = goods.product_sn;
          tjData.product_url = 'product/detail?product_sn=' + goods.product_sn;
          tjData.vr_url = '';
          that.addTj(tjData);
        }
      }
    })
  },
  setLoginByUserInfo: function (openid, userInfo) {
    const that = this;
    wx.request({
      url: app.apiURL + 'auth/getUserInfo',
      data: {
        openid: openid,
        userInfo: userInfo
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        if (res.data) {
          if (res.data.errno == 0) {
            console.log(res.data.data);
            wx.setStorageSync('userInfo', res.data.data);
          }
        }
      }
    })
  },



  initUserInfoFail: function () {
    const that = this;
    wx.showModal({
      title: '警告通知',
      content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                wx.login({
                  success: function (res_login) {
                    if (res_login.code) {
                      wx.getUserInfo({
                        withCredentials: true,
                        success: function (res_user) {
                          console.log("弹窗授权获取用户信息");
                          that.setLoginByWeixin(res_login.code, res_user);
                        }
                      })
                    }
                  }
                });
              }
            }, fail: function (res) {

            }
          })

        }
      }
    })
  },


})